const handleInfluxdbRoute = require('./src/routes/influxdb')
const { URLSearchParams } = require('url')

const serverHandler = (req, res) => {
  res.setHeader('Content-Type', 'application/json')
  res.setHeader('Access-Control-Allow-Origin', '*')

  const url = req.url
  req.path = url.split('?')[0]

  req.query = new URLSearchParams(req.url.split('?')[1])

  const influxdbDataPromise = handleInfluxdbRoute(req, res)

  if (influxdbDataPromise) {
    influxdbDataPromise.then((influxdbData) => {
      res.end(JSON.stringify(influxdbData))
    })
    return
  }

  res.writeHead(404, { 'Content-Type': 'text/plain' })
  res.write('404 Not Found')
  res.end()
}

module.exports = serverHandler
